﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShareMarking.Systems.Service;
using Common.Utilities.Excel;
using System.Text.RegularExpressions;
using Common.Utilities.Excel.Import;
using System.Data;
using ShareMarking.Service;
using ShareMarking.Entity;
using ShareMarking.Interface;
using System.Configuration;
using System.Text;
namespace ShareMarking.Web.admin.EnterPrise.QrStore
{
    public partial class storeimport : ManagePage
    {
        private static string httpstr = ConfigurationManager.AppSettings["vigohttp"];
        private static string signsecret = ConfigurationManager.AppSettings["signscrect"];
        private static string diyhttp = ConfigurationManager.AppSettings["diyhttp"];//本系统网站域名
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
        }

        #region 导入门店信息==================================

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //获取文件路径
            var filepath = Server.MapPath(this.txt_filename.Text.Trim());
            ExcelUtilities util = new ExcelUtilities();
            Excel excel = null;
            //获取配置
            var result = util.ImportExcel(filepath, "storeimport", out excel);
            bool result1 = false;
            bool result2 = false;
            bool result3 = false;
            bool result4 = false;
            if (result.Result == ExcelResultType.Succeed)
            {
                var updatecount = 0;//成功条数
                int errorCount = 0;//失败条数
                var datasource = excel.DataSet;
                if (datasource.Tables.Count > 0)
                {
                    foreach (DataRow row in datasource.Tables[0].Rows)
                    {
                        #region 循环判断更新或增加
                        if (!row[0].ToString().IsNullOrEmpty() && !row[1].ToString().IsNullOrEmpty())
                        {
                            #region 1.判断新增或者更新
                            var strore = qr_StoreService.Instance.Get_SingleEntity_byWhere(qr_Store._.StoreCode == Regex.Replace(row[1].ToString().Trim(), @"\s", ""));
                            if (strore != null)
                            {
                                #region  更新门店 去掉数据源的空格和换行符
                                var entity = qr_StoreService.Instance.Get_SingleEntity_byWhere(qr_Store._.StoreCode == Regex.Replace(row.ItemArray[1].ToString().Trim(), @"\r\n", ""));
                                if (entity != null)
                                {
                                    entity.S_Name = Regex.Replace(row.ItemArray[0].ToString().Trim(), @"\r\n", "");//门店名称
                                    entity.StoreCode = Regex.Replace(row.ItemArray[1].ToString().Trim(), @"\r\n", "");//门店编号
                                    entity.S_Provinces = Regex.Replace(row.ItemArray[2].ToString().Trim(), @"\r\n", "");//门店所属省份
                                    entity.S_City = Regex.Replace(row.ItemArray[3].ToString().Trim(), @"\r\n", "");//门店所属城市
                                    entity.S_Area = Regex.Replace(row.ItemArray[4].ToString().Trim(), @"\r\n", "");//门店所属大区
                                    entity.S_Region = Regex.Replace(row.ItemArray[5].ToString().Trim(), @"\r\n", "");//门店所属片区
                                    entity.A_wxTitle = Regex.Replace(row.ItemArray[6].ToString().Trim(), @"\r\n", "");//微信图文标题
                                    entity.A_wxDesc = Regex.Replace(row.ItemArray[7].ToString().Trim(), @"\r\n", "");//微信图文描述
                                    entity.A_wxUrl = Regex.Replace(row.ItemArray[8].ToString().Trim(), @"\r\n", "");//微信图文链接
                                    entity.A_wxImgUrl = Regex.Replace(row.ItemArray[9].ToString().Trim(), @"\r\n", "");//微信图片地址
                                    entity.ModifiedOn = DateTime.Now;
                                    entity.isneedupdate = false;
                                    entity.isneedupload = true;                                    
                                    result2 = qr_StoreService.Instance.Update_Entity(entity);
                                }
                                #endregion
                            }
                            else
                            {
                                #region 新增门店 去掉数据源的空格和换行符
                                qr_Store store = new qr_Store();
                                store.S_Name = Regex.Replace(row.ItemArray[0].ToString().Trim(), @"\r\n", "");//门店名称
                                store.StoreCode = Regex.Replace(row.ItemArray[1].ToString().Trim(), @"\r\n", "");//门店编号
                                store.S_Provinces = Regex.Replace(row.ItemArray[2].ToString().Trim(), @"\r\n", "");//门店所属省份
                                store.S_City = Regex.Replace(row.ItemArray[3].ToString().Trim(), @"\r\n", "");//门店所属城市
                                store.S_Area = Regex.Replace(row.ItemArray[4].ToString().Trim(), @"\r\n", "");//门店所属大区
                                store.S_Region = Regex.Replace(row.ItemArray[5].ToString().Trim(), @"\r\n", "");//门店所属片区
                                store.A_wxTitle = Regex.Replace(row.ItemArray[6].ToString().Trim(), @"\r\n", "");//微信图文标题
                                store.A_wxDesc = Regex.Replace(row.ItemArray[7].ToString().Trim(), @"\r\n", "");//微信图文描述
                                store.A_wxUrl = Regex.Replace(row.ItemArray[8].ToString().Trim(), @"\r\n", "");//微信图文链接
                                store.A_wxImgUrl = Regex.Replace(row.ItemArray[9].ToString().Trim(), @"\r\n", "");//微信图片地址                               
                                store.CreateOn = DateTime.Now;
                                store.isneedupdate = true;
                                store.isneedupload = true;
                                store.Remark = "DN" + DateTime.Now.ToString("yyyyMMdd");//批次 DN +时间
                                result2 = qr_StoreService.Instance.Add_Entity(store);

                                #endregion
                            }
                            #endregion

                            if (result2)
                            {
                                #region 2.同步二维码
                                var has = qr_QrCodeRelateService.Instance.Get_IsExist_ByWhere(
                                        qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                                        && qr_QrCodeRelate._.rel_Code == Regex.Replace(row[1].ToString().Trim(), @"\s", ""));
                                if (!has)
                                {
                                    #region 如果在关联表没有NC对应的记录，就新增二维码

                                    //查询是否有以前弃用的二维码
                                    var oldqr = qr_QrCodeService.Instance.Get_Entitys_ByTop(1, qr_QrCode._.type == 1002 &&
                                        qr_QrCode._.isdelete == true, qr_QrCode._.scene_id.Asc);

                                    if (oldqr.IsNullOrCountLTE0())
                                    {
                                        #region get sceneid
                                        var sceneid = 0;
                                        qr_QrCodeType type = qr_QrCodeTypeService.Instance.Get_SingleEntity_byWhere(qr_QrCodeType._.QrCodeTypeID == 1002);
                                        sceneid = type.QT_CurrentIndex.ConvertTo<int>() + 1;
                                        #endregion

                                        #region 编辑图文信息

                                        List<ShareMarking.Interface.extra> extra = new List<ShareMarking.Interface.extra>() { 
                                        new ShareMarking.Interface.extra {
                                            title = Regex.Replace(row[6].ToString().Trim(), @"\s", ""),
                                            shortdesc = Regex.Replace(row[7].ToString().Trim(), @"\s", ""), 
                                            linkurl = HttpUtility.UrlDecode((Regex.Replace(row[8].ToString().Trim(), @"\s", "")).Replace('&','$'), Encoding.UTF8),//HttpUtility.UrlDecode((currenturl).Replace('&','$'), Encoding.UTF8),
                                            picurl =diyhttp+ Regex.Replace(row[9].ToString().Trim(), @"\s", "")//"/images/20170524.jpg"
                                        }
                                    };
                                        var message = new message()
                                        {
                                            title = row[1].ToString() + "的二维码",
                                            remark = row[1].ToString() + "的二维码",
                                            sacode = "test",
                                            scene_id = sceneid,
                                            extra = extra
                                        };
                                        #endregion

                                        #region 请求vigo 生成二维码
                                        var vigo = new Qrcode_vigo(httpstr, signsecret);
                                        var resultentity = vigo.CreateQrcode(message);
                                        #endregion

                                        while (resultentity.errcode == "12")
                                        {
                                            ComLib.LogLib.Log4NetBase.Log("错误信息:" + resultentity.errmsg + "/sceneid=" + sceneid);
                                            sceneid += 1;
                                            message.scene_id = sceneid;
                                            resultentity = vigo.CreateQrcode(message);
                                        }

                                        #region 将返回的信息保存
                                        if (resultentity.errcode == "00")
                                        {
                                            #region 保存二维码
                                            qr_QrCode qrcode = new qr_QrCode()
                                            {
                                                id = resultentity.message.id,
                                                type = 1002,
                                                scene_id = resultentity.message.scene_id,
                                                sacode = resultentity.message.sacode,
                                                title = resultentity.message.title,
                                                remark = resultentity.message.remark,
                                                code_url = resultentity.message.code_url,
                                                qrcode_url = resultentity.message.qrcode_url,
                                                addtime = resultentity.message.addtime,
                                                status = resultentity.message.status,
                                                DateModified = DateTime.Now,

                                                wx_title = Regex.Replace(row.ItemArray[6].ToString().Trim(), @"\r\n", ""),//微信图文标题
                                                wx_content = Regex.Replace(row.ItemArray[7].ToString().Trim(), @"\r\n", ""),//微信图文描述
                                                wx_url = Regex.Replace(row.ItemArray[8].ToString().Trim(), @"\r\n", ""),//微信图文链接
                                                wx_imgurl = diyhttp + Regex.Replace(row.ItemArray[9].ToString().Trim(), @"\r\n", ""),////微信图片地址
                                                isdelete = false
                                            };
                                            result1 = qr_QrCodeService.Instance.Add_Entity(qrcode);
                                            #endregion

                                            #region 添加关联
                                            qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                                            {
                                                qr_Type = 1002,//1002是门店
                                                qr_CodeID = resultentity.message.id,
                                                qr_Scene_ID = resultentity.message.scene_id,
                                                rel_Code = row.ItemArray[1].ToString().Trim(),
                                                IsDelete = false,
                                                CreateOn = DateTime.Now
                                            };
                                            result3 = qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                                            #endregion

                                            #region 更改二维码类型表
                                            type.QT_CurrentIndex = sceneid;
                                            type.QT_Used = type.QT_Used + 1;
                                            type.QT_Surplus = type.QT_Surplus - 1;
                                            result4 = qr_QrCodeTypeService.Instance.Update_Entity(type);
                                            #endregion

                                        }
                                        if (result1 && result3 && result4)
                                        {
                                            updatecount += 1;
                                        }
                                        else
                                        {
                                            errorCount += 1;//新增失败
                                            ComLib.LogLib.Log4NetBase.Log("请求VIGO接口新增失败：StoreCode=" + row.ItemArray[1].ToString() + "//result1=" + result1 + "result2=" + result2 + "result3=" + result3);
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        #region 更新
                                        var qr = oldqr[0];
                                        #region 更新二维码

                                        #region 编辑图文信息

                                        var extra = new List<extra>() { 
                                        new ShareMarking.Interface.extra { 
                                            title = Regex.Replace(row.ItemArray[6].ToString().Trim(), @"\s", ""),
                                            shortdesc = Regex.Replace(row.ItemArray[7].ToString().Trim(), @"\s", ""), 
                                            linkurl = Regex.Replace(row.ItemArray[8].ToString().Trim(), @"\s", "").Replace('&','$'),//HttpUtility.UrlDecode((currenturl).Replace('&','$'), Encoding.UTF8),
                                            picurl =diyhttp+ Regex.Replace(row.ItemArray[9].ToString().Trim(), @"\s", "")//"/images/20170524.jpg"
                                        }
                                    };
                                        var message = new message2()
                                        {
                                            id = qr.id.ToString(),
                                            title = row.ItemArray[1].ToString().Trim(),
                                            remark = row.ItemArray[1].ToString().Trim() + "的二维码",
                                            sacode = "test",
                                            extra = extra
                                        };
                                        #endregion

                                        #region 请求vigo 生成二维码
                                        var vigo = new Qrcode_vigo(httpstr, signsecret);
                                        var resultentity = vigo.UpdateQrcode(message);
                                        #endregion

                                        #endregion

                                        if (resultentity.IndexOf("成功") > 0)
                                        {                                          
                                            #region 新建关联
                                            bool resultQr_QrCodeRelate = false;
                                            bool resultQr_QrCode = false;
                                            if (!qr_QrCodeRelateService.Instance.Get_IsExist_ByWhere(qr_QrCodeRelate._.qr_CodeID == qr.id && qr_QrCodeRelate._.qr_Scene_ID == qr.scene_id && qr_QrCodeRelate._.qr_Type==1002))
                                            {
                                                qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                                                {
                                                    qr_Type = 1002,
                                                    qr_CodeID = qr.id,
                                                    qr_Scene_ID = qr.scene_id,
                                                    rel_Code = row.ItemArray[1].ToString().Trim(),
                                                    IsDelete = false,
                                                    CreateOn = DateTime.Now
                                                };
                                                resultQr_QrCodeRelate=qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                                            }
                                            else
                                            {
                                                var qrrelate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(qr_QrCodeRelate._.qr_CodeID == qr.id && qr_QrCodeRelate._.qr_Scene_ID == qr.scene_id && qr_QrCodeRelate._.qr_Type==1002);
                                                if (qrrelate != null)
                                                {
                                                    qrrelate.rel_Code = row.ItemArray[1].ToString().Trim();
                                                    qrrelate.IsDelete = false;
                                                    qrrelate.DateModified = DateTime.Now;
                                                    resultQr_QrCodeRelate = qr_QrCodeRelateService.Instance.Update_Entity(qrrelate);
                                                }                                                
                                                ComLib.LogLib.Log4NetBase.Log("qr_QrCodeRelate已存在qr_CodeID=" + qr.id + ",qr_Scene_ID=" + qr.scene_id);
                                            }
                                            #endregion

                                            #region 更新关联 BUG 修复一直取第一个，导致很多条qr_QrCodeRelate
                                            qr.title = Regex.Replace(row.ItemArray[0].ToString().Trim(), @"\r\n", "");
                                            qr.remark = Regex.Replace(row.ItemArray[0].ToString().Trim(), @"\r\n", "") + "的二维码";
                                            qr.DateModified = DateTime.Now;
                                            qr.wx_title = Regex.Replace(row.ItemArray[6].ToString().Trim(), @"\r\n", "");//微信图文标题
                                            qr.wx_content = Regex.Replace(row.ItemArray[7].ToString().Trim(), @"\r\n", "");//微信图文描述
                                            qr.wx_url = Regex.Replace(row.ItemArray[8].ToString().Trim(), @"\r\n", "");//微信图文链接
                                            qr.wx_imgurl = diyhttp + Regex.Replace(row.ItemArray[9].ToString().Trim(), @"\r\n", "");////微信图片地址
                                            qr.isdelete = false;//已启用旧码
                                            resultQr_QrCode=qr_QrCodeService.Instance.Update_Entity(qr);
                                            
                                            if (resultQr_QrCodeRelate && resultQr_QrCode)
                                            {
                                                updatecount += 1;
                                            }
                                            else {
                                                errorCount += 1;//更新失败
                                                ComLib.LogLib.Log4NetBase.Log("新建关联失败 或者 更新关联失败：resultQr_QrCodeRelate=" + resultQr_QrCodeRelate + "  resultQr_QrCode=" + resultQr_QrCode);
                                            }
                                            #endregion
                                        }
                                        else
                                        {
                                            errorCount += 1;//更新失败
                                            ComLib.LogLib.Log4NetBase.Log("请求VIGO接口更新失败：StoreCode=" + row.ItemArray[1].ToString());
                                        }
                                        #endregion
                                    }
                                    #endregion
                                }
                                else
                                {
                                    #region 如果有了二维码，也更新一次
                                    var relate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                                    qr_QrCodeRelate._.qr_Type == 1002 && qr_QrCodeRelate._.IsDelete == false
                                    && qr_QrCodeRelate._.rel_Code == Regex.Replace(row[1].ToString().Trim(), @"\s", ""));

                                    if (relate != null)
                                    {
                                        var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == relate.qr_CodeID);
                                        if (qrcode != null)
                                        {
                                            #region 更新二维码

                                            #region 编辑图文信息

                                            var extra = new List<extra>() { 
                                                    new ShareMarking.Interface.extra { 
                                                        title = Regex.Replace(row.ItemArray[6].ToString().Trim(), @"\s", ""),
                                                        shortdesc = Regex.Replace(row.ItemArray[7].ToString().Trim(), @"\s", ""), 
                                                        linkurl = Regex.Replace(row.ItemArray[8].ToString().Trim(), @"\s", "").Replace('&','$'),//HttpUtility.UrlDecode((currenturl).Replace('&','$'), Encoding.UTF8),
                                                        picurl =diyhttp+ Regex.Replace(row.ItemArray[9].ToString().Trim(), @"\s", "")//"/images/20170524.jpg"
                                                    }
                                                };
                                            var message = new message2()
                                            {
                                                id = qrcode.id.ToString(),
                                                title = row.ItemArray[1].ToString().Trim(),
                                                remark = row.ItemArray[1].ToString().Trim() + "的二维码",
                                                sacode = "test",
                                                extra = extra
                                            };
                                            #endregion

                                            #region 请求vigo 生成二维码
                                            var vigo = new Qrcode_vigo(httpstr, signsecret);
                                            var resultentity = vigo.UpdateQrcode(message);
                                            if (resultentity.IndexOf("成功") > 0)
                                            {
                                                bool resultQr_QrCode = false;
                                                #region 更新关联 BUG 修复一直取第一个，导致很多条qr_QrCodeRelate
                                                qrcode.title = Regex.Replace(row.ItemArray[0].ToString().Trim(), @"\r\n", "");
                                                qrcode.remark = Regex.Replace(row.ItemArray[0].ToString().Trim(), @"\r\n", "") + "的二维码";
                                                qrcode.DateModified = DateTime.Now;
                                                qrcode.wx_title = Regex.Replace(row.ItemArray[6].ToString().Trim(), @"\r\n", "");//微信图文标题
                                                qrcode.wx_content = Regex.Replace(row.ItemArray[7].ToString().Trim(), @"\r\n", "");//微信图文描述
                                                qrcode.wx_url = Regex.Replace(row.ItemArray[8].ToString().Trim(), @"\r\n", "");//微信图文链接
                                                qrcode.wx_imgurl = diyhttp + Regex.Replace(row.ItemArray[9].ToString().Trim(), @"\r\n", "");////微信图片地址
                                                qrcode.isdelete = false;//已启用旧码
                                                resultQr_QrCode = qr_QrCodeService.Instance.Update_Entity(qrcode);

                                                if (resultQr_QrCode)
                                                {
                                                    updatecount += 1;
                                                    ComLib.LogLib.Log4NetBase.Log("Store二维码修改成功：：：StoreCode:" + row.ItemArray[1].ToString() + "::==sceneid==::" + relate.qr_Scene_ID);
                                                }
                                                else
                                                {
                                                    errorCount += 1;//更新失败
                                                    ComLib.LogLib.Log4NetBase.Log("更新关联失败：resultQr_QrCode=" + resultQr_QrCode);
                                                }
                                                #endregion     
                                            }
                                            else
                                            {
                                                errorCount += 1;//更新失败
                                                ComLib.LogLib.Log4NetBase.Log("请求VIGO接口更新失败：StoreCode=" + row.ItemArray[1].ToString() + "::==sceneid==::" + relate.qr_Scene_ID);
                                            }
                                            #endregion

                                            #endregion
                                        }
                                        else
                                        {
                                            ComLib.LogLib.Log4NetBase.Log("1-3、更新二维码时qr_QrCode表找不到id：::" + relate.qr_CodeID + "---------------");
                                        }
                                    }
                                    else
                                    {
                                        errorCount += 1;
                                        ComLib.LogLib.Log4NetBase.Log("1-3、---------------关联表找不到门店Code：::" + row.ItemArray[1].ToString().Trim() + "---------------");
                                    }
                                    #endregion
                                }
                                #endregion
                            }
                            else
                            {
                                errorCount += 1;//新增或者更新失败
                                ComLib.LogLib.Log4NetBase.Log("新增或者更新失败，StroreCode：" + row.ItemArray[1].ToString().Trim());
                            }
                        }
                        else
                        {
                            errorCount += 1;//失败条数
                            ComLib.LogLib.Log4NetBase.Log("导入失败:不存在记录。");
                        }
                        #endregion
                    }
                }
                JscriptMsg("导入成功" + updatecount + "条，失败" + errorCount + "条！", "Index.aspx", "Success");
                ComLib.LogLib.Log4NetBase.Log("导入成功" + updatecount + "条，失败" + errorCount + "条！");
            }
            else
            {
                //JscriptMsg("wxcodeimport", "导入失败！请检查excel！", "", "Error");
                JscriptMsg("导入失败！请检查excel！", "Index.aspx", "Error");
            }
        }
        #endregion
    }
}